<?php
/**
 * 
 * 截取指定长度的字符串
 * @param string $srcstr
 * @param string $length
 * @param string $ext
 * @return string $srcstr
 */
function trunkString($srcstr, $length, $ext = '...') {
    if (strlen($srcstr) > $length) {
        $ext = trim($ext);
        if (strlen($ext) > 0) {
            $length = $length - 2;
        }

        for($i=0; $i<$length; $i++) {
        	//0x80 即十进制1
            if (ord($srcstr[$i]) > 0x80) {
                $i++;
            }
        }
        if ($i > $length) {
            $length = $length - 1;
        }
        $srcstr = substr($srcstr, 0, $length).$ext;
    }
    return $srcstr;
}


/*
 * 截取指定长度的字符串, 支持中文字符集,要求str编码必须为utf-8
 * @param string $srcstr
 * @param string $length
 * @param string $ext
 * @return string $srcstr
 */

function cutstr($str, $length, $ext='...') {
    $len = strlen($str);
    if($len <= $length) {
        return $str;
    }
    $strcut = '';
    $n = 0;
    $tn = 0;
    $noc = 0;
    while($n < $len) {
        $t = ord($str[$n]);
        if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
            $tn = 1; $n++; $noc++;
        } elseif(194 <= $t && $t <= 223) {
            $tn = 2; $n += 2; $noc += 2;
        } elseif(224 <= $t && $t <= 239) {
            $tn = 3; $n += 3; $noc += 2;
        } elseif(240 <= $t && $t <= 247) {
            $tn = 4; $n += 4; $noc += 2;
        } elseif(248 <= $t && $t <= 251) {
            $tn = 5; $n += 5; $noc += 2;
        } elseif($t == 252 || $t == 253) {
            $tn = 6; $n += 6; $noc += 2;
        } else {
            $n++;
        }
        if($noc >= $length) {
            break;
        }
    }
    if($noc > $length) {
        $n -= $tn;
    }
    $strcut = substr($str, 0, $n);
    return $strcut.$ext;
}

$str = 'This a just a test string for trunk function!';
echo "The original string is :<br />";
echo $str . "<br /><br />";
$aftrunk = trunkString($str, 14);
echo "The string after trunk is :<br />";
echo $aftrunk;
